<template>
  <div>
    <div>
      <nut-tabs background="#fff" title-scroll v-model="aftersaleType" type="smile" swipeable>
        <nut-tab-pane custom-class="custom-tabpane" v-for="(item, index) in  aftersaleTabs " :pane-key="item.value"
          :key="index" :title="item.label">
          <div bg-white>
            <div flex flex-a-c p-16rpx>
              <nut-input v-model="searchForm.keywords" :input-style="searchStyle" :border="false"
                placeholder="请输入订单编号/商品名称/售后编号">
                <template #left>
                  <div pl-18rpx flex flex-a-c> <nut-icon name="search" /> </div>
                </template>
              </nut-input>
              <div @click="search" w-100rpx text-center>搜索</div>
            </div>
          </div>

          <div v-if="isShow" px-16rpx>
            <scroll-view>
              <div v-if="aftersaleList.length" p-32rpx card my-20rpx v-for="(item, index) in  aftersaleList "
                :key="index">
                <div text-24rpx color-warmgray mb-16rpx>
                  订单编号：{{ item.sn }}
                </div>
                <order :res="item" type="afterSale">
                  <template v-if="item.orderItems" #body="data: any">
                    <div flex flex-a-c mt-20rpx justify-end>
                      <div flex flex-a-c gap-24rpx>
                        <nut-button v-if="item.orderItems[data.index].complainStatus == 'NO_APPLY'" plain type="default"
                          @tap.stop="$navigateTo('/pages/mine/sue/apply?sn=' + item.sn + '&skuId=' + item.orderItems[data.index].skuId)"
                          size="small">投诉</nut-button>
                        <div
                          v-if="item.flowPrice != 0 && item.orderItems[data.index]?.afterSaleStatus.includes('NOT_APPLIED') || item.orderItems[data.index]?.afterSaleStatus.includes('PART_AFTER_SALE')">
                          <nut-button size="small"
                            @tap.stop="$navigateTo('/pages/mine/aftersale/apply?sn=' + item.orderItems[data.index].sn + '')"
                            type="primary" plain> 申请售后 </nut-button>
                        </div>
                      </div>
                    </div>
                  </template>

                  <template v-if="item.orderItems" #footer="data: any">

                    <div mt-20rpx>
                      <div flex flex-a-c
                        :class="{ 'flex-j-sb': data.index === item?.orderItems.length - 1, 'justify-end': data.index !== item?.orderItems.length - 1 }">
                        <div text-24rpx v-show="data.index === item.orderItems.length - 1">
                          订单总金额<span ml-10rpx text-28rpx font-bold text-main-color>{{ unitPrice(item.flowPrice, '￥')
                            }}</span>
                        </div>
                        <div ml-20rpx text-24rpx color-warmgray>
                          <span
                            v-if="item.orderItems[data.index]?.afterSaleStatus.includes('ALREADY_APPLIED')">该商品已申请售后服务</span>
                          <span v-if="item.orderItems[data.index]?.afterSaleStatus.includes('EXPIRED')">该商品无法申请售后</span>
                        </div>
                      </div>
                    </div>
                  </template>


                  <template #footer-extra
                    v-if="currentAftersaleType == 'APPLYING' || currentAftersaleType == 'APPLYLOG'">
                    <!-- 微信小程序中如果不写下面这一行代码 退货/退款可能不展示   -->
                    <span v-show="false">{{ item.serviceType }} {{ item.serviceType == 'RETURN_MONEY' }}</span>
                    <div flex flex-a-c flex-j-sb>
                      <div text-24rpx color-black>
                        <div v-if="item.serviceType == 'RETURN_MONEY'">
                          退款-{{ serviceStatusList(item.serviceStatus) }}</div>


                        <div v-if="item.serviceType == 'RETURN_GOODS'">
                          退货处理-{{ serviceStatusList(item.serviceStatus) }}</div>


                        <div v-if="item.serviceType == 'SUPPLY_AGAIN_GOODS'">
                          补发商品-{{ serviceStatusList(item.serviceStatus) }}</div>

                        <div v-if="item.serviceType == 'EXCHANGE_GOODS'">
                          换货-{{ serviceStatusList(item.serviceStatus) }}</div>


                        <div v-if="item.serviceType == 'CANCEL'">
                          取消订单-{{ serviceStatusList(item.serviceStatus) }}</div>
                      </div>
                      <div flex flex-a-c gap-24rpx>

                        <div text-main-color text-24rpx @click="handleClickCancelSale(item)"
                          v-show="currentAftersaleType == 'APPLYING'">
                          取消售后</div>

                        <nut-button plain type="primary" v-if="true"
                          @click="$navigateTo('/pages/mine/aftersale/detail?sn=' + item.sn + '')"
                          size="small">售后详情</nut-button>


                        <nut-button v-if="currentAftersaleType == 'APPLYLOG' && item.serviceStatus &&
        item.serviceStatus == 'PASS' &&
        item.serviceType != 'RETURN_MONEY'" plain type="primary"
                          @click="$navigateTo('/pages/mine/aftersale/express?sn=' + item.sn + '')"
                          size="small">提交物流</nut-button>


                      </div>
                    </div>


                  </template>

                </order>

              </div>
              <div mt-100rpx v-else>
                <empty></empty>
              </div>
            </scroll-view>
          </div>
        </nut-tab-pane>
      </nut-tabs>
    </div>
    <nut-dialog title="提示" content="是否取消该售后服务?" v-model:visible="cancelSale" @ok="confirmCancelSale"></nut-dialog>
    <!-- 加载 -->
    <nut-toast ref="toastRef" />
  </div>
</template>

<script setup lang="ts">
import { getAfterSaleList, } from '@/api/after-sale';
import { getOrderList } from '@/api/member';
import order from "@/components/basic-template/order.vue";
import empty from '@/components/empty/index.vue';
import { colors } from '@/constants/injection-key';
import type { Search } from '@/constants/types';
import { confirmCancelAftersale } from '@/pages/mine/aftersale/operation';
import { serviceStatusList, unitPrice } from '@/utils/filters';
import { onPullDownRefresh, onReachBottom, onShow, onLoad } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';

const routerVal = ref<any>();
const toastRef = ref<ToastInst>()
const cancelSale = ref<boolean>(false)
const searchStyle = {
  'background-color': colors.bgColor,
  'border-radius': '100px',
  'padding': '0 16rpx',
  'height': '64rpx',
  'light-height': '64rpx'
}
const currentData = ref<any>('')
const aftersaleType = ref<string>('APPLY')
const currentAftersaleType = ref<string>('APPLY')

const searchForm = ref<Search>({
  pageNumber: 1,
  pageSize: 20,
  sort: "createTime",
  flowPrice: 0,
  order: "desc",
  keywords: '',  // 搜索关键字
})
const isShow = ref(false)
const aftersaleData = ref<any>('')
const aftersaleList = ref<any>([])
const aftersaleTabs = [
  {
    label: "售后申请",
    value: "APPLY"
  },
  {
    label: "申请中",
    value: "APPLYING"
  },
  {
    label: "申请记录",
    value: "APPLYLOG"
  },]

watch(() => aftersaleType.value, (val) => {
  if (aftersaleType.value != currentAftersaleType.value) {
    currentAftersaleType.value = val
    init()
  }
  
}, { immediate: false })
// 点击取消售后
function handleClickCancelSale(val: any) {
  cancelSale.value = true
  currentData.value = val
}

// 取消售后
async function confirmCancelSale() {

  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const res = await confirmCancelAftersale(currentData.value.sn)
  toastRef.value?.hideToast();

  if (res) {
    init()
  }
}

// 搜索
function search() {
  // searchForm.value.keywords
  init()
}
async function init() {
  isShow.value = false
  aftersaleList.value = []
  searchForm.value.pageNumber = 1
  await fetch()
}
onPullDownRefresh(() => {
  init()
})


async function fetch() {
  uni.stopPullDownRefresh();

  let res: any
  // 如果是售后申请
  if (aftersaleType.value === 'APPLY') {
    const search = {
      ...searchForm.value,
      // tag: "COMPLETE"
    }
    res = await getOrderList(search)
  }
  if (aftersaleType.value === 'APPLYING') {
    const search = {
      ...searchForm.value,
      serviceStatus: "APPLY"
    }
    res = await getAfterSaleList(search)
  }
  if (aftersaleType.value === 'APPLYLOG') {
    const search = {
      ...searchForm.value,
      sort: "createTime",
      order: "desc",
    }
    res = await getAfterSaleList(search)
  }
  isShow.value = true
  if (res.data.success) {
    aftersaleData.value = res.data.result
    aftersaleList.value.push(...res.data.result.records)
  }
}

onReachBottom(() => {
  if (aftersaleData.value?.total > searchForm.value.pageNumber * searchForm.value.pageSize) {
    searchForm.value.pageNumber++;
    fetch()
  }
})

onShow(() => {
  // init()
})

onLoad((options: any) => {
  routerVal.value = options
  searchForm.value.keywords = options.orderSn;
  init();

})
</script>

<style scoped lang="scss"></style>
